package cn.jy.boot.controller;

import com.google.code.kaptcha.Producer;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class VerityCodeController {

    private final Producer producer;

    @Autowired
    public VerityCodeController(Producer producer) {
        this.producer = producer;
    }

    @RequestMapping("/vc")
    public String getVerityCode(HttpServletResponse response, HttpServletRequest request) throws IOException {
//        response.setContentType("image/png");
        String code = producer.createText();//生成验证码
        //将验证码存入session中
        request.getSession().setAttribute("code", code);
        System.out.println(code);
        BufferedImage bi = producer.createImage(code);//将验证码创建为图片
        //2.写入内存
        FastByteArrayOutputStream fos = new FastByteArrayOutputStream();
        ImageIO.write(bi, "png", fos);
        //3.生成 base64
        return Base64.encodeBase64String(fos.toByteArray());
    }

    @RequestMapping("/code")
    public String sessionCode(HttpSession session){
        String code = (String) session.getAttribute("code");
        return code;
    }
}
